package com.example.video.controller;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.video.Enum.videoStatus;
import com.example.video.entity.Video;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Value("${downLoadPath}")
    private String downloadPath;


    /**
     * 从处理视频服务器中接受处理后的视频和对应该资源的信息，并进行保存
     *
     * @param file       处理后的视频
     * @param jsonObject 对应视频的信息
     * @return
     */
    @PostMapping("/video")
    public ResponseEntity uploadVideo(@RequestParam("file") MultipartFile file, @RequestParam Map<String, String> jsonObject) {
        // TODO:对接收到的这个json进行解析，通过其中的id判断视频下载的位置
//        log.info("uploadCtr -> video -> json = " + jsonObject);
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Please select a file to upload.");
        }

        String resourceId = jsonObject.get("id");


        try {
            // 保存处理后的视频
            log.info("uploadCtr -> video -> resourceId = " + resourceId);



            // 根据视频id查找对应数据
            //  /resource/薄荷与巧克力/2024-06-09/799537010-1-208-0-0.mp4
            // 定义正则表达式模式
            String patternStr = "/resource/(.*?)/(.*?)/(.*?.mp4)";

            // 编译正则表达式
            Pattern pattern = Pattern.compile(patternStr);

            // 获取对应资源id的视频
            Video video = Db.lambdaQuery(Video.class)
                    .eq(Video::getResourceId, resourceId)
                    .select(Video::getMedias)
                    .one();
            JSONArray jsonArray = new JSONArray(video.getMedias());
            String url = jsonArray.getJSONObject(0).getString("resource_url");
            log.info("uploadCtr -> video -> url = " + url);

            // 创建匹配器
            Matcher matcher = pattern.matcher(url);
            String userName = "";
            String downDate = "";
            String temp_fileName = "";
            // 查找匹配项并提取所需部分
            if (matcher.find()) {
                userName = matcher.group(1);
                downDate = matcher.group(2);
                temp_fileName = matcher.group(3);
                log.info("uploadCtr -> video -> extractedStr = " + userName);
                log.info("uploadCtr -> video -> dataStr = " + downDate);
                log.info("uploadCtr -> video -> fileName = " + temp_fileName);
            } else {
                log.info("No match found.");
            }

            // 处理后的视频在名字前加  h-
            String fileName = downloadPath + userName + '/' + downDate + "/h-" + temp_fileName;
            log.info("uploadCtr -> video -> video = " + video);
            log.info("uploadCtr -> video -> savePath = " + fileName);
            log.info(new Date()+"\n\n");
            byte[] bytes = file.getBytes();
            Path path = Paths.get(fileName);
            Files.write(path, bytes);

            // 设置该视频的状态为已处理
            Db.lambdaUpdate(Video.class)
                    .eq(Video::getResourceId, resourceId)
                    .set(Video::getStatus, videoStatus.PROCESSED.getStatus())
                    .update();

            return ResponseEntity.ok("视频上传成功！");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败: " + e.getMessage());
        }

    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<String> handleMaxSizeException(MaxUploadSizeExceededException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("文件超出最大可上传大小!");
    }
}
